package com.ken.util;

import com.ken.fx.WebITS;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
import org.openxmlformats.schemas.drawingml.x2006.main.CTTransform2D;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;

public class WordDocumentUtils {

    public static File copyDocument(File inputFile,String from,String to) throws Exception {
        File tempFile = null;
        try {
            // 读取原始Word文档
            FileInputStream fis = new FileInputStream(inputFile);
            XWPFDocument document = new XWPFDocument(fis);

            // 创建新的Word文档
            XWPFDocument newDocument = new XWPFDocument();

            // 遍历段落并复制文本和图片
            List<XWPFParagraph> paragraphs = document.getParagraphs();
            for (XWPFParagraph paragraph : paragraphs) {
                XWPFParagraph newParagraph = newDocument.createParagraph();
                copyParagraphFormatting(paragraph, newParagraph);

                for (XWPFRun run : paragraph.getRuns()) {
                    // 复制文本到新文档并翻译
                    XWPFRun newRun = newParagraph.createRun();
                    copyRunFormatting(run, newRun);

                    String originalText = run.getText(0);
                    if (originalText != null) {
                        String translatedText = WebITS.translation(originalText,from,to);
                        newRun.setText(translatedText);
                    }

                    // 复制图片到新文档
                    for (XWPFPicture picture : run.getEmbeddedPictures()) {
                        XWPFDocument finalNewDocument = newDocument;
                        XWPFDocument finalDocument = document;
                        byte[] pictureBytes = picture.getPictureData().getData();
                        int pictureType = picture.getPictureData().getPictureType();

                        // 获取图片的文档中尺寸
                        CTTransform2D xfrm = picture.getCTPicture().getSpPr().getXfrm();
                        CTPositiveSize2D ext = xfrm.getExt();
                        long cx = ext.getCx();
                        long cy = ext.getCy();

                        String blipId = finalNewDocument.addPictureData(pictureBytes, pictureType);
                        newRun.addPicture(
                                finalDocument.getAllPictures().get(finalDocument.getAllPictures().indexOf(picture.getPictureData())).getPackagePart().getInputStream(),
                                pictureType,
                                picture.getPictureData().getFileName(),
                                Units.toEMU(cx / 12700),  // EMU units conversion
                                Units.toEMU(cy / 12700)
                        );
                    }
                }
            }

            // 创建临时文件
            tempFile = Files.createTempFile("copiedDocument", ".docx").toFile();

            // 写入新文档到临时文件
            FileOutputStream fos = new FileOutputStream(tempFile);
            newDocument.write(fos);

            // 关闭流
            fis.close();
            fos.close();

            System.out.println("Document copying completed successfully!");

            return tempFile;

        } catch (IOException | InvalidFormatException e) {
            e.printStackTrace();
            if (tempFile != null && tempFile.exists()) {
                tempFile.delete();
            }
            return null;
        }
    }

    private static void copyParagraphFormatting(XWPFParagraph sourceParagraph, XWPFParagraph targetParagraph) {
        // 复制段落的对齐方式
        targetParagraph.setAlignment(sourceParagraph.getAlignment());
        targetParagraph.setVerticalAlignment(sourceParagraph.getVerticalAlignment());

        // 复制段落的间距和缩进
        targetParagraph.setSpacingBefore(sourceParagraph.getSpacingBefore());
        targetParagraph.setSpacingAfter(sourceParagraph.getSpacingAfter());
        targetParagraph.setSpacingBetween(sourceParagraph.getSpacingBetween());
        targetParagraph.setIndentationLeft(sourceParagraph.getIndentationLeft());
        targetParagraph.setIndentationRight(sourceParagraph.getIndentationRight());
        targetParagraph.setIndentationHanging(sourceParagraph.getIndentationHanging());
        targetParagraph.setIndentationFirstLine(sourceParagraph.getIndentationFirstLine());

        // 复制段落样式
        if (sourceParagraph.getCTP() != null && sourceParagraph.getCTP().isSetPPr()) {
            CTPPr pPr = sourceParagraph.getCTP().getPPr();
            targetParagraph.getCTP().setPPr(pPr);
        }
    }

    private static void copyRunFormatting(XWPFRun sourceRun, XWPFRun targetRun) {
        targetRun.setBold(sourceRun.isBold());
        targetRun.setItalic(sourceRun.isItalic());
        targetRun.setStrikeThrough(sourceRun.isStrikeThrough());
        targetRun.setUnderline(sourceRun.getUnderline());
        targetRun.setColor(sourceRun.getColor());
        targetRun.setFontFamily(sourceRun.getFontFamily());
        targetRun.setFontSize(sourceRun.getFontSize());

        // 复制CTR中的所有RPr属性
        if (sourceRun.getCTR() != null && sourceRun.getCTR().isSetRPr()) {
            CTRPr rPr = sourceRun.getCTR().getRPr();
            targetRun.getCTR().setRPr(rPr);
        }
    }


}





